package FlowGram.Application.Parser.Actions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import FlowGram.Application.Parser.*;
import FlowGram.Application.Parser.Actions.Control.FunctionDefinition;
import FlowGram.Application.Parser.Controllers.FinchController;


/**
 * 
 * @author thackray
 *
 */
public class FunctionInvocation extends FinchAction {

	
	protected String name;
	protected FunctionDefinition pointer;
	
	public FunctionInvocation() {}
	
	
	public FunctionDefinition getDefinition(){
		return this.pointer;
	}
	public void setDefinition(FunctionDefinition definition){
		this.pointer = definition;
		this.name = this.pointer.getName();
	}
	public String getName(){
		return this.name;
	}
	
	
	public static boolean matches(String s){
		return s.matches("^\\w+");
	}
	public static String syntax(){
		return "<function_name>";
	}
	@Override
	public String toCode(int indent) {
		return this.name;
	}
	@Override
	public String toHTML(String idPrefix){
		return this.toCode();
	}
	@Override
	public void execute(FinchController controller) {
		this.pointer.execute(controller);
	}

	@Override
	public String logMessage() {
		return "function "+this.name;
	}

	@Override
	public void parse(String statement) throws FinchParserException {
		Pattern p = Pattern.compile("^(\\w+)$");
		Matcher matcher = p.matcher(statement);
		while(matcher.find()){
			if(matcher.group(1) != null){
				this.name = matcher.group(1);
				
				this.pointer = FunctionDefinition.findFunction(this.name);
				if(this.pointer == null){
					throw new FinchParserException("Function "+this.name+" has not yet been defined");
				}
			}	
		}
	}

}
